/**
 * Created by zyy on 15/9/8.
 * zhangyuyu@superjia.com
 */
(function($) {
    'use strict';

    var project = {

        collection: new(Backbone.Collection.extend({
            model: Backbone.Model,
            parse: function(response, xhr) {
                if (response.code != 200) {
                    return [];
                }
                var items = response.data;
                if (!items) return response;
                _.each(items, function(item) {

                });

                return items;
            }
        })),

        api: function(key) {
            var rootPath = '/api/project';
            return rootPath + {
                list: '',
                create: '/create'
            }[key];
        },

        init: function(container, options) {
            var self = this;
            self.container = container;
            self.options = options;

            container.html(tpl);

            self.listPanel = container.find('.list');

            self.collection.bind('reset', self.addItems, self);
            self.collection.bind('add', self.addItem, self);

            self.events();
            self.load();
        },

        load: function(callback) {
            var self = this;
            var container = self.container;
            var options = self.options;

            self.collection.fetch({
                url: self.api('list'),
                method: 'get',
                success: function(collection, response, opt) {
                    if(options.projectId) {
                        self.selectItem(options.projectId);
                    }
                },
                error: function() {
                    callback && callback(null)
                }
            })
        },

        events: function() {
            var self = this;
            var container = self.container;

            container.on('click', '.create-btn', function() {
                var dialog = self.createdialog = new App.common.Dialog({
                    title: '创建项目',
                    isConfirm: true,
                    message: createTpl,
                    okCallback: function() {
                        var nameInput = dialog.find('input[name="name"]');
                        var name = $.trim(nameInput.val());
                        if (name) {
                            self.createProject(name);
                        }
                        return false;
                    }
                });
            });
        },

        setOptions: function(options) {
            this.options = $.extend({}, this.options, options);
        },

        selectItem: function(projectId) {
            var self = this;
            var collection = self.collection;
            collection.where({_id: projectId})[0].trigger('selected');
        },

        createProject: function(name) {
            var self = this;

            $.ajax({
                url: self.api('create'),
                type: 'post',
                data: {
                    name: name
                },
                success: function(res) {
                    if (res.code == 200) {
                        self.collection.add([res.data]);
                        self.createdialog.close();
                    }
                }
            });
        },

        addItems: function(collection, options) {
            var self = this
            collection.each(function(model) {
                self.addItem(model, collection)
            });
        },

        addItem: function(model, collection, options) {
            var self = this
            var view = new projectView({
                model: model
            })
            self.listPanel.append(view.render().$el);
        }
    };

    var projectView = Backbone.View.extend({
        className: 'project-item stateful',
        events: {
            'click': 'itemClickHandler',
            'click .checkbox': 'checkboxHandler'
        },
        initialize: function() {
            var self = this
            self.listenTo(self.model, 'change', self.render);
            self.listenTo(self.model, 'selected', self.selected);
        },
        render: function() {
            var self = this
            var data = self.model.toJSON();


            self.$el.html(template.draw(itemTpl, data)).attr('href', '/project/' + data._id);

            return self
        },
        itemClickHandler: function() {
            var self = this
            var data = null
            var item = data = self.model.toJSON();

            self.selected();
        },
        selected: function() {
            this.$el.siblings().removeClass('active').end().addClass('active');
        }
    });

    var tpl = '' +
        '<div class="mod-project">' +
        '   <div class="create-btn btn btn-primary">创建项目</div>' +
        '   <div class="list"></div>' +
        '</div>';

    var createTpl = '' +
        '<div class="project-create">' +
        '   <input name="name" autofocus class="form-control" placeholder="项目名称"/>' +
        '</div>';

    var itemTpl = '' +
        '<span>{{name}}</span>'

    App.modules.project = project;
})(jQuery);
